package com.financing.platform.web.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.SMSDict;
import com.financing.platform.SMSSend;
import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.dto.FaRevisitTaskDTO;
import com.financing.platform.dto.SwitchDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IFaRevisitTaskService;
import com.financing.platform.service.ISwitchService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.StringUtil;

@Controller("faRevisitTaskController")
@RequestMapping("/api/faRevisitTask")
public class FaRevisitTaskController extends BaseAction  { 

	private Logger logger = Logger.getLogger(getClass());
	@Autowired
	ISwitchService switchSerivceImpl;
	
	//未处理
	String FAREVISIT_STATUS_1 = "1";
	//已处理
	String FAREVISIT_STATUS_2 = "2";
	//处理失败
	String FAREVISIT_STATUS_3="3";
	
	@Autowired
	private IFaRevisitTaskService faRevisitTaskService;
	
	@RequestMapping("/listFaRevisitTask.shtml")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, FaRevisitTaskDTO faRevisitTask,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query faRevisitTask list begin .......");
			
			faRevisitTask.setBegin(pager.getStartIndex());
			faRevisitTask.setPageSize(pager.getPageSize());
			
			//当前登录用户id
			UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			faRevisitTask.setFaRevisitUser(userinfo.getUserId());
			faRevisitTask.setDeleteTag("1");
			//未处理的待办事项
			faRevisitTask.setFaRevisitStatus(FAREVISIT_STATUS_1);
			
			int count = faRevisitTaskService.queryListCount(faRevisitTask);
			
			pager.setTotalCount(count);
			
			List<FaRevisitTaskDTO> faRevisitTaskList = null;
			
			if(count > 0){
				faRevisitTaskList = faRevisitTaskService.queryList(faRevisitTask);
			}else{
				faRevisitTaskList = Collections.emptyList();
			}
			result.setAttribute("pager", pager);
			result.setAttribute("list", faRevisitTaskList);
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query faRevisitTask list end .......");
		}catch(Exception e){
			log.error("query faRevisitTask error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return result;
	}
	@RequestMapping("/updateFaRevisitTask.shtml")
	@ResponseBody
	public ResultMap update(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info(" updateFaRevisitTask begin .......");
			
			String id = request.getParameter("id");
			if(StringUtil.isNullOrEmptyNStr(id)){
				result.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			FaRevisitTaskDTO faRevisitTask = faRevisitTaskService.loadById(Integer.parseInt(id));
			if(faRevisitTask==null||faRevisitTask.getId()==null){
				result.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			//当前登录用户id
			UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			String userId = userinfo.getUserId();
			if(!faRevisitTask.getFaRevisitUser().equals(userId)){
				result.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//标记已处理
			faRevisitTask.setFaRevisitStatus(FAREVISIT_STATUS_2);
			DTOdateSet.setUpdateInfo(faRevisitTask,request.getSession());
			
			faRevisitTaskService.update(faRevisitTask);
			
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("updateFaRevisitTask end .......");
		}catch(Exception e){
			log.error("updateFaRevisitTask error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return result;
	}
	/***
	 * 新增待办事项或者发送短信
	 * @param request
	 * @param faRevisitTask
	 * @return
	 */
	@RequestMapping("/addFaRevisitTask.shtml")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, FaRevisitTaskDTO faRevisitTask){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add faRevisitTask  begin .......");
			
			String faRevisitContent = faRevisitTask.getFaRevisitContent();
			String faRevisitDate = faRevisitTask.getFaRevisitDate();
			String faRevisitPhone = faRevisitTask.getFaRevisitPhone();
			String faRevisitType = faRevisitTask.getFaRevisitType();
			String faRevisitUserId = faRevisitTask.getFaRevisitUserId();
			//空参数  和  type 仅支持 发送短信和待办
			if(StringUtil.isNullOrEmptyNStr(faRevisitType,faRevisitContent)||!faRevisitType.matches("1|2")){
				result.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			//类型1发送短信2待办
			if("1".equals(faRevisitType)){
				if(StringUtils.isBlank(faRevisitPhone)||!faRevisitPhone.matches("\\d{11}")){
					result.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				//开关设置
				//判断短信开关是否打开，打开则发送，不打开则永久不发送
				SwitchDTO switchs = new SwitchDTO();
				switchs.setsKey("faRevisitSendSMS");
				switchs = switchSerivceImpl.querySwitch(switchs);
				
				Map<String,Object> res = new HashMap<String,Object>();
				if(Dict.switchOn.equals(switchs.getsValue())){
					SMSSend smsSend = new SMSSend();
					List<String>  mobileList = new ArrayList<String>();
					mobileList.add(faRevisitPhone);
					//发送短信
					try {
						res=smsSend.sendSMS(mobileList, faRevisitContent);
					} catch (Exception e) {
						logger.error("send sms error!",e);
					}
				}else{
					log.info("switch is off ");
					res.put(SMSDict.result, Dict.sms_send_success);
				}
				if(Dict.sms_send_success.equals(res.get(SMSDict.result))){
					//已处理
					faRevisitTask.setFaRevisitStatus(FAREVISIT_STATUS_1);
					result.setAttribute("sendStatus","0");
				}else{
					//处理失败
					faRevisitTask.setFaRevisitStatus(FAREVISIT_STATUS_3);
					result.setAttribute("sendStatus","-1");
				}
			}else{
				if(StringUtil.isNullOrEmptyNStr(faRevisitDate,faRevisitUserId)||!faRevisitDate.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}")){
					result.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				Date revisitDate = DateUtil.parseDateString(faRevisitDate,"yyyy-MM-dd HH:mm");
				Date nowdate=new Date();
				if(nowdate.after(revisitDate)){
					result.setStatusCode(ResultCode.STATUS_CODE_TIME_ERROR);
					result.setStatus(ResultMap.STATUS.FAILE);
					return result;
				}
				
				//未处理
				faRevisitTask.setFaRevisitStatus(FAREVISIT_STATUS_1);
				result.setAttribute("sendStatus","0");
			}
			//当前登录用户id
			UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			faRevisitTask.setFaRevisitUser(userinfo.getUserId());
			
			faRevisitTask.setDeleteTag("1");
			DTOdateSet.setCreateInfo(faRevisitTask,request.getSession());
			DTOdateSet.setUpdateInfo(faRevisitTask,request.getSession());
			
			int id = faRevisitTaskService.insert(faRevisitTask);
			result.setAttribute("id", id);
			
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add faRevisitTask list end .......");
		}catch(Exception e){
			log.error("add faRevisitTask error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return result;
	}
}
